package com.lihua.newideas.service.impl;

import com.lihua.newideas.pojo.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

//根据账号查询用户信息  String s s是用户输入的账号名，账号存在后输入的密码会跟数据库经行匹配
@Service
public class MyUserDetailsServiceImpl  implements UserDetailsService {


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    MyUserServiceImpl serviceImple;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        MyUser myuser = serviceImple.queryUserByName(s);
        //1、更具用户们查询，如果不存在着UsernameNotFoundException抛出异常
//        System.out.println(myuser);
        if(myuser==null){
//            System.out.println(myuser);
            throw new UsernameNotFoundException("用户不存在");
        }

        //加密密码（注册时密码已经加密过了）如果数据库中的密码没有加密，需要先将密码加密。
        // 如果匹配成功返回UserDetail
//        String password = passwordEncoder.encode(myuser.getPass());

        //注意这里的User是security自带的
//        return new User(s,password, AuthorityUtils.commaSeparatedStringToAuthorityList(myuser.getAuthority()));//赋予权限
//        return new User(s,password, AuthorityUtils.commaSeparatedStringToAuthorityList(myuser.getVip()));//赋予角色
        return new User(s,myuser.getPassWord(), AuthorityUtils.commaSeparatedStringToAuthorityList(myuser.getVip()+","+myuser.getAuthority()));//拼接
    }
}
